﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;

namespace KinConquer.Packets.Handles
{
    public class LoginRequest
    {
        public unsafe static void Handle(Byte* Data, KinSocket.Connection Client)
        {
            Structures.LoginRequest* Request = (Structures.LoginRequest*)Data;

            String[] Info = new String[] {
                Request->User,
                KinSocket.Encryption.PasswordEncryption.Decrypt(1, Request->User, KinSocket.PacketConstructor.PointerToArray(Data)),
                Request->Server
            };

            Structures.LoginResponse Response = Structures.LoginResponse.Create();

            UInt32 responseValue = 54;
            MySqlDataReader reader = null;
            if (Program.Database.ExecuteReader("SELECT id,type FROM account WHERE username = '" + Info[0] + "' AND password = '" + Info[1] + "'", ref reader) == 0)
            {
                if (reader != null)
                {
                    if (reader.Read())
                    {
                        UInt32 type = Convert.ToUInt32(reader["type"]);
                        UInt32 id = Convert.ToUInt32(reader["id"]);
                        if (type != 255)
                        {
                            Response.Seed = 1;
                            Response.GamePort = Variables.GamePort;
                            Response.IPAddress = Variables.GameIP;
                            responseValue = Convert.ToUInt32(reader["id"]);

                            MySqlDataReader authCheck = null;

                            Program.Database.ExecuteReader("SELECT identifier,time FROM authenticate WHERE identifier=" + id, ref authCheck);
                            if (authCheck == null || !authCheck.Read())
                            {
                                if (authCheck != null)
                                    authCheck.Close();
                                Program.Database.ExecuteNonQuery("INSERT INTO authenticate VALUES(" + id + ", CURTIME())");
                            }
                        }
                        else responseValue = 12;
                    }
                    else
                        responseValue = 1;
                    reader.Close();
                }
            }
            Response.Identifier = responseValue;
            Client.Send(&Response);
        }
    }
}
